﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Prepare.Domain.Entities;
using Prepare.Domain.Abstract;
using System.Net.Mail;
using System.Net;

namespace Prepare.Domain.Concrete
{
	public class MailMan : IMailMan
	{
		private EmailSettings emailSettings;

		public MailMan(EmailSettings settings)
		{
			emailSettings = settings;
		}

		public void ProcessOrder(ShippingDetails shippingInfo)
		{
			using (var smtpClient = new SmtpClient())
			{
				smtpClient.EnableSsl = emailSettings.UseSsl;
				smtpClient.Host = emailSettings.ServerName;
				smtpClient.Port = emailSettings.ServerPort;
				smtpClient.UseDefaultCredentials = false;
				smtpClient.Credentials = new NetworkCredential(emailSettings.Username, emailSettings.Password);

				if (emailSettings.WriteAsFile)
				{
					smtpClient.DeliveryMethod = SmtpDeliveryMethod.SpecifiedPickupDirectory;
					smtpClient.PickupDirectoryLocation = emailSettings.FileLocation;
					smtpClient.EnableSsl = false;
				}

				StringBuilder body = new StringBuilder()
					.AppendLine("A new order has been submitted")
					.AppendLine("----------");

				MailMessage mailMessage = new MailMessage(
					emailSettings.MailFromAddress,   // From
					emailSettings.MailToAddress,     // To
					"New order submitted",           // Subject
					body.ToString());                // Body

				if (emailSettings.WriteAsFile)
				{
					mailMessage.BodyEncoding = Encoding.ASCII;
				}
				else
				{
					smtpClient.Send(mailMessage);
				}
			}
		}
	}
}